package com.baizhi.controller;

import com.baizhi.dto.request.ChangePasswordDTO;
import com.baizhi.dto.request.UserLoginDTO;
import com.baizhi.dto.response.UserResponseDTO;
import com.baizhi.entity.User;
import com.baizhi.exception.CodeEnum;
import com.baizhi.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@Tag(name="用户管理模块", description = "用户管理模块的控制器")
public class UserController {

    @Autowired
    private UserService userService;

    @PutMapping("/user/changePass")
    public ResponseEntity<CodeEnum> changePassword(@RequestBody @Valid ChangePasswordDTO changePasswordDTO){
        boolean flag = userService.changePassword(changePasswordDTO.getUserId(), changePasswordDTO.getOldPassword(), changePasswordDTO.getNewPassword());
        if(flag){
            return new ResponseEntity<>(CodeEnum.success, HttpStatusCode.valueOf(200));
        }else{
            return new ResponseEntity<>(CodeEnum.password_update_fail,HttpStatusCode.valueOf(500));
        }
    }

    @PutMapping("/user/update")
    public ResponseEntity<CodeEnum> updateUser(@RequestBody @Valid User user){
        boolean flag = userService.updateUser(user);
        if(flag){
            return new ResponseEntity<>(CodeEnum.success,HttpStatusCode.valueOf(200));
        }else{
            return new ResponseEntity<>(CodeEnum.user_update_fail,HttpStatusCode.valueOf(500));
        }
    }

    @GetMapping("/user/getById")
    public User getUserByUserId(@RequestParam("userId") Integer userId){
        User user = userService.getById(userId);
        //清除敏感信息
        user.setPassword(null);
        user.setSalt(null);
        user.setGmtCreate(null);
        user.setGmtModified(null);

        return user;
    }

    @PostMapping("/user/login")
    public ResponseEntity<UserResponseDTO> login(@RequestBody @Valid UserLoginDTO userLoginDTO){

        UserResponseDTO ud = userService.loginUser(userLoginDTO.getUsername(), userLoginDTO.getPassword());
        if(ud != null){
            return new ResponseEntity<>(ud, HttpStatusCode.valueOf(200));
        }else{
            return new ResponseEntity<>(null,HttpStatusCode.valueOf(400));
        }

    }
}
